package com.yzt.index;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.yzt.zhuju.IService.message.IMessageService;
import com.yzt.zhuju.arouter.RouterMain;
import com.yzt.zhuju.base.BaseActivity;
import com.yzt.zhuju.config.AppConfigCacheManager;
import com.yzt.zhuju.dialog.CenterBaseDialog;
import com.yzt.zhuju.dialog.EditDialogFragment;
import com.yzt.zhuju.event.RxBus;
import com.yzt.zhuju.event.main.ExitAppEvent;
import com.yzt.zhuju.network.HttpUrlConfig;
import com.yzt.zhuju.network.HttpUrlManager;
import com.yzt.zhuju.utils.AppDialogUtil;
import com.yzt.p_base.utils.AppInfoUtils;
import com.yzt.p_base.utils.SharedPreferenceUtil;
import com.yzt.p_base.utils.ToastUtil;

/**
 * author : bob
 * date   : 2022/11/30
 * desc   :
 */
public class TestUserSettingActivity extends BaseActivity {

    private Button mTestBtn;

    private Button mZhengShiBtn;

    private EditText mIpTextEt;

    private EditText mH5TextEt;

    private TextView tvEnvironmentText;

    @Autowired
    IMessageService messageService;

    public static void start(Activity activity) {
        Intent intent = new Intent(activity, TestUserSettingActivity.class);
        activity.startActivity(intent);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_test_user_setting;
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void installViews() {
        mTitleBar.setTitle("app相关设置");

        mTestBtn = findViewById(R.id.test_btn);
        mTestBtn.setText("选择测试环境");
        mZhengShiBtn = findViewById(R.id.zhengshi_btn);
        mZhengShiBtn.setText("选择正式环境");

        mIpTextEt = findViewById(R.id.ip_text_et);
        mH5TextEt = findViewById(R.id.h5_text_et);

        ((TextView) findViewById(R.id.test_ip_tv)).setText("测试链接：" + HttpUrlConfig.TEST_URL);
        ((TextView) findViewById(R.id.zhengshi_ip_tv)).setText("正式链接：" + HttpUrlConfig.NORMAL_URL);
        ((TextView) findViewById(R.id.kaifa_ip_tv)).setText("开发链接：" + HttpUrlConfig.DEV_URL);
        ((TextView) findViewById(R.id.pack_name_tv)).setText(AppInfoUtils.getAppPackageName());
        ((TextView) findViewById(R.id.version_name_tv)).setText(AppInfoUtils.getAppVersionName(mActivity) + "\t\t(" + AppInfoUtils.getAppVersionCode(mActivity) + ")");
        ((TextView) findViewById(R.id.channel_tv)).setText(AppInfoUtils.getAppMetaData("UMENG_CHANNEL"));
        ((TextView) findViewById(R.id.http_tv)).setText(HttpUrlManager.getAppHttpUrl(

        ));

        mTestBtn.setOnClickListener(this);
        mZhengShiBtn.setOnClickListener(this);
        findViewById(R.id.update_channel_layout).setOnClickListener(this);
        findViewById(R.id.save_btn).setOnClickListener(this);
        findViewById(R.id.open_btn).setOnClickListener(this);
        findViewById(R.id.kaifa_btn).setOnClickListener(this);

        tvEnvironmentText = findViewById(R.id.tv_environment_text);
        updateEnvironmentShow();
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view.getId() == R.id.update_channel_layout) {
            EditDialogFragment dialogFragment = (EditDialogFragment) CenterBaseDialog.showDialog(mActivity, EditDialogFragment.class);
            dialogFragment.setListener(content -> {
                SharedPreferenceUtil.getInstance().putValue("app_channel", content);
                ((TextView) findViewById(R.id.channel_tv)).setText(AppInfoUtils.getAppMetaData("UMENG_CHANNEL"));
                ToastUtil.showMessage("设置成功");
            });
        } else if (view.getId() == R.id.test_btn) {
            switchEnvironment(2, HttpUrlConfig.TEST_URL);
        } else if (view.getId() == R.id.zhengshi_btn) {
            switchEnvironment(1, HttpUrlConfig.NORMAL_URL);
        } else if (view.getId() == R.id.kaifa_btn) {
            switchEnvironment(0, HttpUrlConfig.DEV_URL);
        } else if (view.getId() == R.id.save_btn) {
            String ipUrl = mIpTextEt.getText().toString().trim();
            if (TextUtils.isEmpty(ipUrl)) {
                ToastUtil.showMessage("请输入ip端口，或者是域名");
                return;
            }
            StringBuffer sb = new StringBuffer();
            sb.append("http://");
            sb.append(ipUrl);
            sb.append("/");
            HttpUrlManager.saveHttpUrl(sb.toString());
            ((TextView) findViewById(R.id.http_tv)).setText(HttpUrlManager.getAppHttpUrl());
            login(sb.toString());
        } else if (view.getId() == R.id.open_btn) {
            String h5Url = mH5TextEt.getText().toString().trim();
            if (TextUtils.isEmpty(h5Url)) {
                ToastUtil.showMessage("请求链接不能为空");
                return;
            }
            RouterMain.goToWeb(h5Url);
        }
    }

    public void login(String ip) {
        AppDialogUtil.showTitleDialog(mActivity, "修改了环境，立刻重新登录app？", ip, mActivity.getString(R.string.cancel),
                mActivity.getString(R.string.sure), new AppDialogUtil.DialogClickInterface() {
                    @Override
                    public void onCancelClick() {

                    }

                    @Override
                    public void onSureClick() {
                        AppConfigCacheManager.getInstance().init();
                        Log.i("gz-base", "testactivity logout");
                        RxBus.getDefault().post(new ExitAppEvent());
                        finish();
                    }
                });
    }

    public void login2(String ip) {
        AppDialogUtil.showTitleDialog(mActivity, "修改了环境，需要重启app？", ip, mActivity.getString(R.string.cancel),
                mActivity.getString(R.string.sure), new AppDialogUtil.DialogClickInterface() {
                    @Override
                    public void onCancelClick() {
                        reStart();
                    }

                    @Override
                    public void onSureClick() {
                        reStart();
                    }
                });
    }

    private void switchEnvironment(int type, String ip) {
        int lastType = HttpUrlManager.getEnvironment();

        boolean isExit = lastType != type && lastType + type >= 2;

        HttpUrlManager.saveEnvironment(type);
        updateEnvironmentShow();

        HttpUrlManager.saveHttpUrl(ip);
        ((TextView) findViewById(R.id.http_tv)).setText(HttpUrlManager.getAppHttpUrl());
        if (isExit) {
            login2(ip);
        } else {
            login(ip);
        }

    }

    private void updateEnvironmentShow() {
        //        0 开发环境 ， 1正式环境  2测试环境
        int mm = HttpUrlManager.getEnvironment();
        String mmTT = "";
        if (mm == 0) {
            mmTT = "开发环境";
        } else if (mm == 1) {
            mmTT = "正式环境";
        } else if (mm == 2) {
            mmTT = "测试环境";
        }
        tvEnvironmentText.setText(mmTT);
    }

    public void reStart() {
        messageService.logout();
        Intent i = this.getPackageManager()
                .getLaunchIntentForPackage(this.getPackageName());
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        this.startActivity(i);
        System.exit(0);
        android.os.Process.killProcess(android.os.Process.myPid());
    }
}
